package com.xzcs.interceptor;

import com.xzcs.util.spring.PropertyUtils;
import com.xzcs.util.web.RequestUtils;
import com.xzcs.util.web.SessionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 微信Oauth2授权拦截器
 * @author chang
 */
public class WeiXinOauth2Interceptor extends HandlerInterceptorAdapter {
	protected Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	public PropertyUtils propertyUtils;
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		String reqUrl = String.valueOf(request.getRequestURL());
		String reqParams = request.getQueryString();
		String reqMethod = request.getMethod();
		boolean isWx = RequestUtils.isWeixRequest(request);
		String app = propertyUtils.getPropertyValue("xzcs.site.app");
		HttpSession httpSession = request.getSession();
		String openId = SessionUtils.getAttribute(httpSession, "openId");
		logger.debug("openId:"+openId+"isWx:"+isWx+"reqMethod:"+reqMethod+"reqUrl:"+reqUrl+"?"+reqParams);
		if (isWx && reqMethod.equals("GET") && openId.equals("")) {
			String redirect = app + "/weixin/service/oauth2.do?"+reqParams+"&purl="+reqUrl;
			//logger.debug("redirect:"+redirect);
			response.sendRedirect(redirect);
			return false;
		}
		return super.preHandle(request, response, handler);
	}
}